const fetch = require('node-fetch');
const fs = require('fs');

// 定义基础URL
const baseUrl = 'http://www.biyu11.com/index.php?m=content&c=index&a=ajaxgod';

async function fetchLunarData(year, month, day) {
    const url = `${baseUrl}&year=${year}&month=${month}&riqi=${year}${month.toString().padStart(2, '0')}${day.toString().padStart(2, '0')}`;
    try {
        let response = await fetch(url);
        if (!response.ok) throw new Error(`Error fetching data for ${year}-${month}-${day}`);
        let data = await response.json();
        return data;
    } catch (error) {
        console.error(`Failed to fetch data for ${year}-${month}-${day}:`, error.message);
        return null;
    }
}

async function collectFebruaryLunarData(year = 2025, month = 2) {
    let lunarDataList = [];
    
    // 假设非闰年2月
    let daysInMonth = 29; // 2025年2月有29天
    
    for (let day = 1; day <= daysInMonth; day++) {
        let data = await fetchLunarData(year, month, day);
        if (data) {
            lunarDataList.push({ date: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`, ...data });
        }
    }

    // 按日期排序（如果需要的话，这里默认已按顺序收集）
    lunarDataList.sort((a, b) => new Date(a.date) - new Date(b.date));

    return lunarDataList;
}

// 查询参数
const year = 2026;
const month = 1;

// 调用函数并打印结果
collectFebruaryLunarData(year, month).then(data => {
    const jsonData = JSON.stringify(data, null, 2);
    // console.log(jsonData);

    // 根据年月动态生成文件名
    const fileName = `lunar_data_${year}_${month.toString().padStart(2, '0')}.json`;

    // 将结果写入json文件
    fs.writeFile(fileName, jsonData, (err) => {
        if (err) {
            console.error('Error writing JSON file:', err);
        } else {
            console.log(`Successfully wrote JSON file: ${fileName}`);
        }
    });
}).catch(error => {
    console.error('Error during processing:', error);
});